package com.wcsy.myblog.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wcsy.myblog.entity.User;
import com.wcsy.myblog.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUserService iUserService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权！");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        //获得当前用户的user对象
        User principal = (User) subject.getPrincipal();
        //给当前用户授权
        info.addStringPermission("user:"+principal.getUserAuthority());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证！");
        //获得前端的用户名和密码
        UsernamePasswordToken user = (UsernamePasswordToken) token;
        User one = iUserService.getOne(new QueryWrapper<User>().eq("ph_number",user.getUsername()));
        if (one == null){
            return  null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user",one);  //保存用户的登陆信息
        //根据用户名进行加密加盐
        String pwd = new SimpleHash("md5",user.getPassword(), ByteSource.Util.bytes(one.getUserName()),5).toString();
        user.setPassword(pwd.toCharArray());
        return new SimpleAuthenticationInfo(one,one.getPassword(),ByteSource.Util.bytes(one.getUserName()),getName());
    }
}
